package com.xw.Controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.xw.Beans.SaveMail;
import com.xw.Beans.SendingMail;
import com.xw.Contents.RetCodeEnums;
import com.xw.Model.JsonResponse;
import com.xw.Model.Page;
import com.xw.Model.api.MailAttachment;
import com.xw.Model.api.SendMailApiModel;
import com.xw.Service.MailService;
import com.xw.Utils.StrUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 描述:邮件网关对外开放的接口控制器
 * @author 杨建全
 * @date 2017年4月6日 上午10:07:43
 */
@RestController
@RequestMapping("/mail")
@Api("邮件网关接口")
public class MailController {
	
	Logger logger = LoggerFactory.getLogger(MailController.class);
	@Autowired
	private MailService mailService;
	
	@PostMapping("/send")
	@ApiOperation(value="发送邮件接口",notes="发送邮件接口接口",httpMethod="POST",produces=MediaType.APPLICATION_JSON_VALUE)
	public JsonResponse sendMail(@ApiParam(name="mail",value="发送邮件的实体") @Valid @RequestBody SendMailApiModel param,BindingResult result) {
		if (result.hasErrors()) {
			JsonResponse failedRet = validParamFailed(result);
			return failedRet;
		}
		//校验邮件地址合法性
		List<String> addressList = getMailAddress(param);
		if(!checkEmailAddress(addressList)){
			return new JsonResponse(RetCodeEnums.FAILED,"邮件地址校验不合法！");
		}
		param.getMail().setReplyMailId("20625");
		boolean flag = mailService.sendMail(param.getMailBox(), param.getMail()); 
		if (!flag) {
			return new JsonResponse(RetCodeEnums.FAILED,"发送失败，可能是邮箱不存在！");
		}
		return new JsonResponse(RetCodeEnums.SUCCESS,"调用接口成功！");
	}
	
	@GetMapping("/downloadFile")
	public void downloadFile(HttpServletRequest request,HttpServletResponse response) throws Exception {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");  
		response.addHeader("Content-Type", "application/octet-stream");
		response.addHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode("UnionAccess接口文档.docx", "UTF-8"));
		
		
		FileInputStream fis = new FileInputStream(new File("D://fileServer//UnionAccess接口文档.docx"));
		IOUtils.copy(fis, response.getOutputStream());
	}
	
	
	
	@GetMapping("/testsend")
	@ApiOperation(value="发送邮件接口",notes="发送邮件接口接口",httpMethod="GET",produces=MediaType.APPLICATION_JSON_VALUE)
	public JsonResponse testsend() throws UnsupportedEncodingException {
		SendMailApiModel param = new SendMailApiModel();
		
		SendingMail mail = new SendingMail();
		mail.setFromUser("hbyangjianquan@outlook.com");
		mail.setHtml("中文附件测试");
		mail.setSubject("中文附件乱码");
		mail.setToUsers(Arrays.asList("916137521@qq.com","nifeng_zero@outlook.com"));
		MailAttachment at = new MailAttachment();
		at.setDescription("UnionAccess接口文档.docx");
		at.setName("UnionAccess接口文档.docx");
		at.setUrl("http://localhost:8501/OpenMail/mail/downloadFile");
		mail.setAttachmentList(Arrays.asList(at));
		
		param.setMail(mail);
		param.setMailBox("hbyangjianquan@outlook.com");
		
		boolean flag = mailService.sendMail(param.getMailBox(), param.getMail()); 
		if (!flag) {
			return new JsonResponse(RetCodeEnums.FAILED,"发送失败，可能是邮箱不存在！");
		}
		return new JsonResponse(RetCodeEnums.SUCCESS,"调用接口成功！");
	}

	/**
	 * 描述：获取邮件的全部地址
	 * @author 杨建全
	 * @date 2017年6月30日
	 * @param param
	 * @return
	 */
	private List<String> getMailAddress(SendMailApiModel param) {
		List<String> bccUsers = param.getMail().getBccUsers();
		List<String> toUsersList = param.getMail().getToUsers();
		List<String> ccUsers = param.getMail().getCcUsers();
		List<String> addressList = new ArrayList<>();
		if (null!=bccUsers && !bccUsers.isEmpty()) {
			addressList.addAll(bccUsers);
		}
		if (null!=toUsersList && !bccUsers.isEmpty()) {
			addressList.addAll(toUsersList);
		}
		if (null!=ccUsers && !bccUsers.isEmpty()) {
			addressList.addAll(ccUsers);
		}
		return addressList;
	}

	@GetMapping("/detail/{mailId}")
	@ApiOperation(value="获取邮件详情",notes="获取邮件详情接口",httpMethod="GET",produces=MediaType.APPLICATION_JSON_VALUE)
	public JsonResponse mailDetail(@ApiParam(name="mailId",value="邮件id") @PathVariable(value="mailId") String mailId){
		SaveMail mail = mailService.getMailById(mailId);
		return new JsonResponse(RetCodeEnums.SUCCESS,mail,"调用成功");
	}
	
	@GetMapping("/all")
	@ApiOperation(value="获取所以邮件列表",notes="获取所以邮件列表接口",httpMethod="GET",produces=MediaType.APPLICATION_JSON_VALUE)
	public Page<SaveMail> getAllMails(
			@ApiParam(name="current",value="当前页") @RequestParam(value="current", required=false, defaultValue="1") Integer current,
			@ApiParam(name="pageSize",value="每页大小") @RequestParam(value="pageSize", required=false, defaultValue="10") Integer pageSize,
			@ApiParam(name="order",value="排序方式") @RequestParam(value="order", required=false, defaultValue="asc") String order){
		Page<SaveMail> page = mailService.getMailPage(new Page<SaveMail>(current, pageSize));
		return page;
	}
	
	/**
	 * 描述：校验参数失败之后封装返回值
	 * @author 杨建全
	 * @date 2017年2月23日
	 * @param result 错误对象
	 * @return
	 */
	private JsonResponse validParamFailed(BindingResult result) {
		List<String> errorMsg = new ArrayList<>();
		for (ObjectError error : result.getAllErrors()) {
			errorMsg.add(error.getDefaultMessage());
		}
		JsonResponse failedRet = new JsonResponse(RetCodeEnums.INVALID_PARAM,errorMsg,"参数校验不通过！");
		logger.info("参数校验失败！"+failedRet);
		return failedRet;
	}
	
	/**
	 * 描述：校验email地址
	 * @author 杨建全
	 * @date 2017年6月30日
	 * @param addressList
	 * @return
	 */
	private boolean checkEmailAddress(List<String> addressList) {
		for (String address : addressList) {
			if (StringUtils.isNotEmpty(address)) {
				boolean checkResult = StrUtil.checkEmaile(address);
				if (!checkResult) {
					return false;
				}
			}
		}
		return true;
	}
}
